var newVoteTask = new Object();
var contacts;
var voteTaskList;
var lastVoteTaskTitle;
var voteTaskDetail;
var voteOptionList;
var myVoteList;
var myVoteDetail;
var voteResult;
$(document)
		.ready(
				function() {
					$(document).click(function(event) {
						$("#voteUserbook").hide();
						$("#voteaddExeDiv").hide();
						$("#voteaddRdrDiv").hide();
					});

					var op = createOperation('getContacts');
					getJson(op, function(data) {
						if (data.status == 0) {
							contacts = data.entity;
							var us = new userSelector('voteTreeview-checkable',
									contacts);
							us.setData(contacts);
							us.setUserTree('voteTreeview-checkable');
							us.onNodeSelected = function(event, node) {
								$("#voteTargetUser").html(node.text);
								newVoteTask.implementId = node.id;
								$("#voteUserbook").hide();
							}
							us.show();
						} else
							alert(data.message);
					});
					getVoteTaskList();

					$("#voteUserbook").click(function(e) {
						e.stopPropagation();
					});
					$("#voteTargetUser").click(function(e) {
						e.stopPropagation();
						$("#voteUserbook").show();
					});
					$("#newVoteTaskTitle")
							.keypress(
									function(ev) {
										// alert("回车:keyCode="+ev.keyCode+"key="+ev.key);
										if (ev.keyCode == 13) {
											if ($(this).val() == "") {
												alert("输入为空");
												return;
											}
											if ($(this).val() == lastVoteTaskTitle) {
												warn("请勿重复创建任务！");
												$(this).val("");
												return;
											}
											// alert("qingqiu");
											// newVoteTask.userId = 0;
											newVoteTask.title = $(this).val();
											newVoteTask.deadLine = $(
													"#newVoteTaskDate").val();
											// newVoteTask.deadLine="2017-12-12";
											newVoteTask.voteType = 0;
											newVoteTask.completion = "0/0";
											getJson(
													createOperation(
															'addVoteTask',
															newVoteTask),
													function(data) {
														if (data.status == 0) {
															// getTaskList();
															addNewVoteTaskNode(
																	correctTaskItem(data.entity),
																	$(
																			"#voteTaskListTable")
																			.DataTable());
															lastVoteTaskTitle = data.entity.voteTask.title;
															$(
																	"#newVoteTaskTitle")
																	.val("");
															// alert("添加一个新任务");
														} else
															warn(data.message);
													}, function(status, err) {
														warn("REQ STAT="
																+ status
																+ "\nERR:"
																+ err);
													});
										}
									});

				});

function getJson(operation, successCallback, errorCallback) {
	$.ajax({
		method : 'POST',
		url : 'Gate',
		dataType : 'json',
		data : {
			req : JSON.stringify(operation)
		},
		success : function(data) {
			if (successCallback)
				successCallback(data)
		},
		error : function(xhr, status, err) {
			if (errorCallback)
				errorCallback(status, err);
		}
	});
	// $.getJSON('Gate', { req: JSON.stringify(operation) }, function (data) {
	// callback(data);
	// });
}

function createOperation(op, obj) {
	var oper = new Object();
	oper.operation = op;
	oper.jsonObject = obj || {
		'na' : 'na'
	};
	return oper;
}
// 获取用户的投票任务列表
function getVoteTaskList() {
	// alert("getVoteTaskList开始执行");
	var op = createOperation('getVoteList');
	getJson(op, function(data) {
		if (data.status == 0) {
			// 判断用户是否已经有创建或者分阅的投票任务，如果空， 跳过showTable
			voteTaskList = data.entity;
			// showTable(prepareTaskTable(taskList));
			for ( var i in voteTaskList) {
				correctTaskItem(voteTaskList[i]);
			}
			showTable(voteTaskList);
		}
	});
}

function correctTaskItem(t) {
	if (t) {
		if (t.voteTask.deadLine == undefined)
			t.voteTask.deadLine = null;
		if (t.voteTask.voteType == 0) {
			t.voteTask.voteType == "分值型";
		} else {
			t.voteTask.voteType == "多选型";
		}
	}
	return t;
}

function addNewVoteTaskNode(t, table) {
	if (!t || !table) {
		warn("new task node error. t=" + t + " table=" + table);
		return;
	}
	var rowNode = table.row.add(t).draw().node();
	table.order([ 4, 'desc' ]).draw();

	$(rowNode).css('color', 'red').animate({
		color : 'black'
	});

}

function showTable(data) {
	// alert(JSON.stringify(data));
	$.fn.dataTable.ext.errMode = 'none';
	var voteTaskTable = $('#voteTaskListTable')
			.DataTable(
					{
						"data" : data,
						"columns" : [
								{
									"data" : 'voteTask.title',
									// "width" : "40%",
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											// alert(JSON.stringify(row.voteTask));
											if (row.voteTask.ownerId == thisUser.id) {
												return "<tr class=\"odd gradeX\"><td class=\"center\"><a style=\"cursor:pointer\" class=\"voteTaskListTitle\" data-id="
														+ row.voteTask.id
														+ ">"
														+ data + "</a></td>";

											} else {
												return "<tr class=\"odd gradeX\"><td class=\"center\">"
														+ data + "</a></td>";
											}

										} else {
											return data;
										}
									}
								},
								{
									"data" : 'owner.name',
									// "width" : "60%",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										}
										return data;
									}
								},
								{
									"data" : 'voteTask.completion',
									// "width" : "10%",
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										}
										return data;
									}
								},
								{
									"data" : 'voteTask.voteType',
									// "width" : "10%",
									// "orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											if (data == 0) {
												return "<td class=\"center\">"
														+ "分值型" + "</td>";
											} else {
												return "<td class=\"center\">"
														+ "多选型" + "</td>";
											}
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'voteTask.createtime',
									// "width" : "20%",
									// "orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'voteTask.deadLine',
									// "width" : "30%",
									// "orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'voteTask.id',
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											if (row.voteTask.ownerId == thisUser.id) {
												return "<td><button type=\"submit\" class=\"btn btn-default\" onclick=\"doDisVoteTask("
														+ data
														+ ")\">投票结果</button><button type=\"submit\" class=\"btn btn-default\" onclick=\"doVoteTaskEdit("
														+ data
														+ ")\">修改</button><button type=\"submit\" class=\"btn btn-default del\" onclick=\"doVoteTaskDel("
														+ data
														+ ")\">删除</button>"
														+ "</td></tr>";
											} else {
												return "<td><button type=\"submit\" class=\"btn btn-default\" onclick=\"doDisVoteTask("
														+ data
														+ ")\">投票结果</button></td></tr>";
											}
										}
										return '';
									}
								} ],
						"order" : [ 4, 'desc' ],
						"oLanguage" : {// 语言设置
							"sLengthMenu" : "每页显示 _MENU_ 条记录",
							"sZeroRecords" : "没有检索到数据",
							"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
							"sInfoEmtpy" : "没有数据",
							"sProcessing" : '<i class="fa fa-coffee"></i> 正在加载数据...',
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "<span class=\"fa fa-chevron-left\">",
								"sNext" : "<span class=\"fa fa-chevron-right\">",
								"sLast" : "尾页"
							},
							"sSearch" : "搜索 "
						},
						"drawCallback" : function(settings) {
							$(".voteTaskListTitle").click(data, function(ev) {
								showVoteTaskDetail($(this).data("id"));
							});
						}
					});
}
// 投票管理页面 每个任务后面的修改按钮事件
function doVoteTaskEdit(id) {
	showVoteTaskDetail(id);
}

// 删除投票任务
function doVoteTaskDel(id) {
	var result = confirm("请确认删除该任务！");
	if (result) {
		request = new Object();
		request.operation = "delVoteTask";
		request.jsonObject = new Object();
		request.jsonObject.voteId = id;

		$.post("Gate", {
			req : JSON.stringify(request)
		}, function(data, status) {
			if (status == "success") {
				var resp = eval("(" + data + ')');
				if (resp.status == 0) {
					// alert("删除成功");
					$("#page-wrapper").load("parts/voteManage.html");
				} else {
					alert("删除失败，错误原因：" + resp.message);
					// $("#page-wrapper").load("parts/teamManage.html");
				}
			} else {
				alert("HTTP请求异常，请重新登陆！");
				self.location = "login.html";
			}
		});
	}
}

// ---------------------------首页用到的方法-----------------------------------------

function getVoteTaskDetail(tmp, callback) {
	var request = createOperation('getVote', {
		voteId : tmp
	});
	$.getJSON("Gate", {
		req : JSON.stringify(request)
	}, function(data) {
		// alert(data.entity);
		callback(data);
	});
}

function showVoteTaskDetail(id) {
	$("#votetTaskListWrapper").load("parts/voteManageEdit.html", function() {
		var vtId = id;
		var view;
		var table_str;
		getVoteTaskDetail(vtId, function(data) {
			voteTaskDetail = data.entity;
			voteOptionList = data.entity.voteOp;
			// alert("主程序" + voteTaskDetail);
			renderVoteTaskView();
			$("#voteTaskTitle").val(voteTaskDetail.voteTask.title);
			// 将数据库的date转换为可以赋值给input date的格式
			// alert(dateChg(voteTaskDetail.voteTask.deadLine));
			$("#voteTaskDateEdit").val(voteTaskDetail.voteTask.deadLine);
			$("#votetDescrEditor").val(voteTaskDetail.voteTask.description);
			if (voteOptionList == undefined) {

			} else {
				showVoteOptionTable(voteOptionList);
			}
		});
	});
}

function renderVoteTaskView() {
	// alert("renderTaskView开始");
	var exeUserbook = new userSelector();
	exeUserbook.setData(contacts);
	var rdrUserbook = new userSelector();
	rdrUserbook.setData(contacts);

	renderExecutors();
	renderReaders();

	// 投票任务参与人设置
	function renderExecutors() {
		// alert("投票任务参与人设置开始执行");
		drawExeList();
		$("#voteaddExeDiv").click(function(e) {
			e.stopPropagation();
		});
		$("#vote-btn-exe-add").click(function(e) {
			e.stopPropagation();
			$("#voteaddRdrDiv").hide();
			exeUserbook.setSelectedUsers(getVoteTaskImpUserIds());
			exeUserbook.setUserTree('voteaddExeNotebook');
			exeUserbook.setMultiSelect(true);
			exeUserbook.onNodeSelected = function(ev, node) {
				addVoteExecutor(node.id, function(data) {
					if (data.status == 0) {
						// TODO
						addImpToVoteTask(data.entity);
						drawExeList();
					}
				}, function(status, err) {
					warn(status + "\n" + err);
				});
			}
			exeUserbook.onNodeUnselected = function(ev, node) {
				delVoteExecutor(node.id, function(data) {
					if (data.status == 0) {
						removeImpFromTaskTask(node.id);
						drawExeList();
					}
				}, function(status, err) {
					warn(status + "\n" + err);
				})
			}
			$("#voteaddExeDiv").show();
			exeUserbook.show();
		});
	}

	// 投票结果查看人设置
	function renderReaders() {
		// alert("添加查看人");
		drawRdrList();
		$("#voteaddRdrDiv").click(function(e) {
			e.stopPropagation();
		});
		$("#vote-btn-rdr-add").click(function(e) {
			e.stopPropagation();
			$("#voteaddExeDiv").hide();
			rdrUserbook.setSelectedUsers(getVoteTaskRdrUserIds());
			rdrUserbook.setUserTree('voteaddRdrNotebook');
			rdrUserbook.setMultiSelect(true);
			rdrUserbook.onNodeSelected = function(ev, node) {
				addVoteReader(node.id, function(data) {
					if (data.status == 0) {
						addRdrToVoteTask({
							id : node.id,
							name : node.text
						});
						drawRdrList();
					}
				}, function(status, err) {
					warn(status + "\n" + err);
				});
			}
			rdrUserbook.onNodeUnselected = function(ev, node) {
				delVoteReader(node.id, function(data) {
					if (data.status == 0) {
						removeRdrFromVoteTask(node.id);
						drawRdrList();
					}
				}, function(status, err) {
					warn(status + "\n" + err);
				});
			}
			rdrUserbook.show();
			$("#voteaddRdrDiv").show();
		});
	}

	function drawRdrList() {
		var rdrListStr = "";
		for ( var i in voteTaskDetail.voteReaList) {
			rdrListStr += '<span class="fa fa-close rdrDel" data-del-uid="'
					+ voteTaskDetail.voteReaList[i].id
					+ '"></span><span class="fa fa-user taskReader"></span>'
					+ voteTaskDetail.voteReaList[i].name;
		}
		$("#votereaderDiv").html(rdrListStr);
		$(".rdrDel").click(function() {
			var uid = $(this).data("del-uid");
			delReader(uid, function(data) {
				if (data.status == 0) {
					removeRdrFromVoteTask(uid);
					drawRdrList();
				}
			}, function(status, err) {
				warn(status + "\n" + err);
			});
		});
	}
	function drawExeList() {
		// alert("drawExeList开始执行");
		var impListStr = "";
		for ( var i in voteTaskDetail.voteImpList) {
			impListStr += '<span class="fa fa-close exeDel" data-del-uid="'
					+ voteTaskDetail.voteImpList[i].id
					+ '"></span><span class="fa fa-user taskExecutor"></span>'
					+ voteTaskDetail.voteImpList[i].name;
		}
		$("#voteexecutorDiv").html(impListStr);
		$(".exeDel").click(function() {
			var uid = $(this).data("del-uid");
			delVoteExecutor(uid, function(data) {
				if (data.status == 0) {
					removeImpFromVoteTask(uid);
					drawExeList();
				}
			}, function(status, err) {
				warn(status + "\n" + err);
			});
		});
	}
}

function delVoteExecutor(uid, callback, errCallback) {
	// callback({ status: 0 });
	var op = createOperation('chgVoteImplement', {
		voteId : voteTaskDetail.voteTask.id,
		action : 0,
		userId : uid
	});
	getJson(op, callback, errCallback);
}
function delVoteReader(uid, callback, errCallback) {
	// callback({ status: 0 });
	var op = createOperation('chgVoteReader', {
		voteId : voteTaskDetail.voteTask.id,
		action : 0,
		userId : uid
	});
	getJson(op, callback, errCallback);
}
function addVoteExecutor(uid, callback, errCallback) {
	// callback({ status: 0 });
	var op = createOperation('chgVoteImplement', {
		voteId : voteTaskDetail.voteTask.id,
		action : 1,
		userId : uid
	});
	getJson(op, callback, errCallback);
}
function addVoteReader(uid, callback, errCallback) {
	// callback({ status: 0 });
	var op = createOperation('chgVoteReader', {
		voteId : voteTaskDetail.voteTask.id,
		action : 1,
		userId : uid
	});
	getJson(op, callback, errCallback);
}

function removeImpFromVoteTask(uid) {
	for (var i = 0; i < voteTaskDetail.voteImpList.length; i++) {
		if (uid == voteTaskDetail.voteImpList[i].id) {
			voteTaskDetail.voteImpList.splice(i, 1);
			return;
		}
	}
}
function removeRdrFromVoteTask(uid) {
	for (var i = 0; i < voteTaskDetail.voteReaList.length; i++) {
		if (uid == voteTaskDetail.voteReaList[i].id) {
			voteTaskDetail.voteReaList.splice(i, 1);
			return;
		}
	}
}
function addImpToVoteTask(u) {
	if (voteTaskDetail.voteImpList == undefined) {
		voteTaskDetail.voteImpList = new Array();
	}
	voteTaskDetail.voteImpList.push(u);
}
function addRdrToVoteTask(u) {
	if (voteTaskDetail.voteReaList == undefined) {
		voteTaskDetail.voteReaList = new Array();
	}
	voteTaskDetail.voteReaList.push(u);
}

function getVoteTaskImpUserIds() {
	var ids = new Array();
	if (!voteTaskDetail.voteImpList)
		return ids;
	for (var i = 0; i < voteTaskDetail.voteImpList.length; i++) {
		ids.push(voteTaskDetail.voteImpList[i].id);
	}
	return ids;
}
function getVoteTaskRdrUserIds() {
	var ids = new Array();
	if (!voteTaskDetail.voteReaList)
		return ids;
	for (var i = 0; i < voteTaskDetail.voteReaList.length; i++) {
		ids.push(voteTaskDetail.voteReaList[i].id);
	}
	return ids;
}

function showVoteOptionTable(data) {
	var i = 1;
	$('#voteOption-example')
			.DataTable(
					{
						"data" : data,
						"columns" : [
								{
									"data" : 'id',
									"width" : "50px",
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<tr class=\"odd gradeX\"><td class=\"center\">"
													+ (i++) + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'voteOptionName',
									"width" : "150px",
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										}
										return data;
									}
								},
								{
									"data" : 'id',
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											return "<td></button><button type=\"submit\" class=\"btn btn-default\" onclick=doVoteOptionEdit("
													+ data
													+ ");>修改</button><button type=\"submit\" class=\"btn btn-default\" onclick=doVoteOptionDel("
													+ data
													+ ");>删除</button></td></tr>";
										}
										return '';
									}
								} ],
						"order" : [ 0, 'asc' ],
						"oLanguage" : {// 语言设置
							"sLengthMenu" : "每页显示 _MENU_ 条记录",
							"sZeroRecords" : "没有检索到数据",
							"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
							"sInfoEmtpy" : "没有数据",
							"sProcessing" : '<i class="fa fa-coffee"></i> 正在加载数据...',
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "<span class=\"fa fa-chevron-left\">",
								"sNext" : "<span class=\"fa fa-chevron-right\">",
								"sLast" : "尾页"
							},
							"sSearch" : "搜索 "
						}
					});
}

// 投票管理 投票修改 增加选项
function addVoteOption() {
	var name = prompt("请输入选项名称", "");
	if (name) {
		var op = createOperation('addVoteOption', {
			voteId : voteTaskDetail.voteTask.id,
			voteOptionName : name
		});
		getJson(op, function(data) {
			if (data.status == 0) {
				voteOptionList = data.entity;
				showVoteTaskDetail(voteTaskDetail.voteTask.id);

				// $('#voteOption-example').DataTable().fnClearTable();
				// $('#voteOption-example').DataTable().fnDestroy();
				// showVoteOptionTable(data.entity);
				// $('#voteOption-example').DataTable().ajax.reload(null,false);

			}
		});
	}
}
// 修改投票选项
function doVoteOptionEdit(id) {
	var name = prompt("请输入选项名称", "");
	if (name) {
		var op = createOperation('chgVoteOption', {
			voteId : voteTaskDetail.voteTask.id,
			voteOptionName : name,
			id : id
		});
		getJson(op, function(data) {
			if (data.status == 0) {
				showVoteTaskDetail(voteTaskDetail.voteTask.id);
				// showVoteOptionTable(data.entity);
				voteOptionList = data.entity;
				// alert(voteOptionList);
			}
		});
	}

}
// 删除选项
function doVoteOptionDel(id) {
	var op = createOperation('delVoteOption', {
		voteId : voteTaskDetail.voteTask.id,
		id : id
	});
	getJson(op, function(data) {
		if (data.status == 0) {
			showVoteTaskDetail(voteTaskDetail.voteTask.id);
			voteOptionList = data.entity;

		}
	});
}

// 编辑页面点击确认，保存后返回该voteTask实体
$("#doVoteManageEditCon").click(function() {
	var op = createOperation('chgVoteTask', {
		voteId : voteTaskDetail.voteTask.id,
		description : $("#votetDescrEditor").val(),
		title : $("#voteTaskTitle").val(),
		deadLine : $("#voteTaskDateEdit").val(),
		voteType : 0

	});
	getJson(op, function(data) {
		if (data.status == 0) {
			alert("修改成功！");
			showVoteTaskDetail(data.entity.id);
		}
	});
});

// 编辑页面点击删除，不返回。
$("#doVoteManageDelCon").click(function() {
	var result = confirm("是否删除任务： " + voteTaskDetail.voteTask.title + "？");
	if (result) {
		var op = createOperation('delVoteTask', {
			voteId : voteTaskDetail.voteTask.id
		});
		getJson(op, function(data) {
			if (data.status == 0) {
				$("#page-wrapper").load("parts/voteManage.html");
			}
		});
	}
});

// 编辑页面点击返回，回到管理页面。
function doVoteManageEditCan() {
	$("#page-wrapper").load("parts/voteManage.html");
}

// 页面顶部投票管理
$("#loadVoteManageButton").click(function(e) {
	$("#page-wrapper").load("parts/voteManage.html");
});

// 页面顶部-我的投票
$("#loadMyTask").click(function() {
	// $("#page-wrapper").load("parts/voteManage.html");
});

// 参与投票 页面 数据加载
function loadVoteManageMyVote() {

	request = new Object();
	request.operation = "getMyVoteList";
	request.jsonObject = new Object();
	request.jsonObject.na = "na";
	$.post("Gate", {
		req : JSON.stringify(request)
	}, function(data, status) {
		if (status == "success") {
			var resp = eval("(" + data + ')');
			if (resp.status == 0) {
				showMyVoteListTable(resp.entity);

			} else {
				alert("获取我的投票，错误原因：" + resp.message);
			}
		} else {
			alert("HTTP请求异常，请重新登陆！");
			self.location = "login.html";
		}
	});

}

function showMyVoteListTable(data) {
	// alert(JSON.stringify(data));
	$('#myVoteTaskListTable')
			.DataTable(
					{
						"data" : data,
						"columns" : [
								{
									"data" : 'vote.title',
									"width" : "250px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<tr class=\"odd gradeX\"><td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'vote.voteType',
									"width" : "80px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											if (data == 0) {
												return "<td class=\"center\">"
														+ "分值型" + "</td>";
											} else {
												return "<td class=\"center\">"
														+ "选择型" + "</td>";
											}
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'owner',
									"width" : "60px",
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'vote.createtime',
									"width" : "160px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'vote.deadLine',
									"width" : "150px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'completion',
									"width" : "100px",
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											if (data == 0) {
												return "<td class=\"center\">"
														+ "否" + "</td>";
											} else {
												return "<td class=\"center\">"
														+ "是" + "</td>";
											}
										}
										return data;
									}
								},
								{
									"data" : 'vote.id',
									"orderable" : false,
									"render" : function(data, type, row, meta) {
										if (type === "display") {
											if (row.completion == 1) {
												return "<td><button type=\"submit\" class=\"btn btn-default\" onclick=doMyVoteView("
														+ data
														+ ")>查看</button></td></tr>";
											} else {
												return "<td><button type=\"submit\" class=\"btn btn-default\" onclick=doMyVoteEdit("
														+ data
														+ ")>投票</button></td></tr>";
											}
										}
										return '';
									}
								} ],
						"order" : [ 3, 'asc' ],
						"oLanguage" : {// 语言设置
							"sLengthMenu" : "每页显示 _MENU_ 条记录",
							"sZeroRecords" : "没有检索到数据",
							"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
							"sInfoEmtpy" : "没有数据",
							"sProcessing" : '<i class="fa fa-coffee"></i> 正在加载数据...',
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "<span class=\"fa fa-chevron-left\">",
								"sNext" : "<span class=\"fa fa-chevron-right\">",
								"sLast" : "尾页"
							},
							"sSearch" : "搜索 "
						}
					});
}

// 跳转至投票页面
function doMyVoteEdit(id) {
	$("#myVoteManage")
			.load(
					"parts/voteMyVote.html",
					function() {
						request = new Object();
						request.operation = "getVote";
						request.jsonObject = new Object();
						request.jsonObject.voteId = id;
						$
								.post(
										"Gate",
										{
											req : JSON.stringify(request)
										},
										function(data, status) {
											// var voteTaskDetail;
											if (status == "success") {
												var resp = eval("(" + data
														+ ')');
												if (resp.status == 0) {
													myVoteDetail = resp.entity;
													$("#myVoteTitle")
															.text(
																	myVoteDetail.voteTask.title);
													$("#myVoteOwner")
															.text(
																	myVoteDetail.user.name);
													$("#myVoteDeadLine")
															.text(
																	myVoteDetail.voteTask.deadLine);
													if (myVoteDetail.voteTask.voteType == 0) {
														$("#myVotetype").text(
																"分值型");
													} else {
														$("#myVotetype").text(
																"选择型");
													}
													$("#myVotetDescr")
															.text(
																	myVoteDetail.voteTask.description);

													var table_str = "";
													for (var i = 0; i < myVoteDetail.voteOp.length; i++) {
														table_str = table_str
																+ "<tr class=\"odd gradeX\"><td class=\"center\">"
																+ (i + 1)
																+ "</td><td class=\"center\">"
																+ myVoteDetail.voteOp[i].voteOptionName
																+ "</td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=0></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=1></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=2></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=3></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=4></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=5></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=6></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=7></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=8></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=9></td><td class=\"center\"><input type=\"radio\" name=\"opList"
																+ (i + 1)
																+ "\" value=10></td></tr>";
													}
													document
															.getElementById("myVoteOptionsBody").innerHTML = table_str;
													document
															.getElementById("buttonControl").innerHTML = "<button id=\"myVoteCon\" type=\"submit\" class=\"btn btn-default\" onclick=\"myVoteCon()\">确认</button><button id=\"myVoteCan\" type=\"submit\" class=\"btn btn-default\" onclick=\"myVoteCan()\">返回</button>";

												} else {
													alert("获取我的投票，错误原因："
															+ resp.message);
												}
											} else {
												alert("HTTP请求异常，请重新登陆！");
												self.location = "login.html";
											}
										});
					});
}

// 参与投票 页面的查看本人本次任务的投票结果按键 事件
function doMyVoteView(id) {
	// alert("查看已经完成的 我的投票任务");
	$("#myVoteManage")
			.load(
					"parts/voteMyVote.html",
					function() {
						request = new Object();
						request.operation = "getVote";
						request.jsonObject = new Object();
						request.jsonObject.voteId = id;
						$
								.post(
										"Gate",
										{
											req : JSON.stringify(request)
										},
										function(data, status) {
											// var voteTaskDetail;
											if (status == "success") {
												var resp = eval("(" + data
														+ ')');
												if (resp.status == 0) {
													myVoteDetail = resp.entity;
													$("#myVoteTitle")
															.text(
																	myVoteDetail.voteTask.title);
													$("#myVoteOwner")
															.text(
																	myVoteDetail.user.name);
													$("#myVoteDeadLine")
															.text(
																	myVoteDetail.voteTask.deadLine);
													if (myVoteDetail.voteTask.voteType == 0) {
														$("#myVotetype").text(
																"分值型");
													} else {
														$("#myVotetype").text(
																"选择型");
													}
													$("#myVotetDescr")
															.text(
																	myVoteDetail.voteTask.description);

													// 中间需要补充内容，添加子页面
													$("#VDSwitch")
															.load(
																	"parts/voteManageViewResultsSelect.html",
																	function() {
																		request = new Object();
																		request.operation = "getVoteScoreDetail";
																		request.jsonObject = new Object();
																		request.jsonObject.userId = thisUser.id;
																		request.jsonObject.voteId = myVoteDetail.voteTask.id;
																		$
																				.post(
																						"Gate",
																						{
																							req : JSON
																									.stringify(request)
																						},
																						function(
																								data,
																								status) {
																							if (status == "success") {
																								var resp = eval("("
																										+ data
																										+ ')');
																								// alert(resp.entity);
																								viewResultsTaskOptionsPer(resp.entity);

																								// viewResultsTaskOptions(thisUser.id,myVoteDetail.voteTask.id);
																								if (resp.status == 0) {

																								} else {
																									alert("获取我的投票，错误原因："
																											+ resp.message);
																								}
																							} else {
																								alert("HTTP请求异常，请重新登陆！");
																								self.location = "login.html";
																							}
																						});

																	});
													// 个人投票结果查看页面，只留返回按钮

													document
															.getElementById("buttonControl").innerHTML = "<button id=\"myVoteCan\" type=\"submit\" class=\"btn btn-default\" onclick=\"myVoteCan()\">返回</button>";

												} else {
													alert("获取我的投票，错误原因："
															+ resp.message);
												}
											} else {
												alert("HTTP请求异常，请重新登陆！");
												self.location = "login.html";
											}
										});
					});
}

// 投票选项点击事件处理函数，将该radio设置为选中，该行的其他radio取消选中
$("input").click(function() {
	$(this).attr("checked", "checked");
	$("input:radio[name=" + $(this).name + "]").attr("checked", false);
});

// 完成投票后的确认事件
function myVoteCon() {
	// 创建一个ArrayList,用于存储投票结果对象
	var optionResults = new Array();
	var booleanTmp = true;
	for (var i = 0; i < myVoteDetail.voteOp.length; i++) {
		var map = new Object();
		// alert(JSON.stringify(myVoteDetail.voteOp[i]));
		map.voteOptionId = myVoteDetail.voteOp[i].id;
		// alert( $("input[name=\"opList1\"]:checked").val());
		map.voteScore = $("input:radio[name=\"opList" + (i + 1) + "\"]:checked")
				.val();
		if (map.voteScore == undefined) {
			alert("第" + (i + 1) + "项未评分，请返回修改！");
			booleanTmp = false;
			break;
		}
		optionResults.push(map);
	}
	if (booleanTmp) {
		// alert("数据收集完成");
		request = new Object();
		request.operation = "addVoteScore";
		request.jsonObject = new Object();
		request.jsonObject.voteId = myVoteDetail.voteTask.id;
		request.jsonObject.results = optionResults;
		$.post("Gate", {
			req : JSON.stringify(request)
		}, function(data, status) {
			if (status == "success") {
				var resp = eval("(" + data + ')');
				if (resp.status == 0) {
					alert("投票成功！");
					$("#page-wrapper").load("parts/voteManageMyVote.html");
				} else {
					alert("投票失败，错误原因：" + resp.message);
				}
			} else {
				alert("HTTP请求异常，请重新登陆！");
				self.location = "login.html";
			}
		});
	}
}

// 点击投票管理的结果按钮，打开任务结果查看界面，加载结果，用于创建者及分阅者查看
function doDisVoteTask(id) {
	// alert(id);
	$("#votetTaskListWrapper")
			.load(
					"parts/voteManageViewResults.html",
					function() {
						request = new Object();
						request.operation = "getVoteScore";
						request.jsonObject = new Object();
						request.jsonObject.voteId = id;
						$
								.post(
										"Gate",
										{
											// async : false,
											req : JSON.stringify(request)
										},
										function(data, status) {
											if (status == "success") {
												var resp = eval("(" + data
														+ ')');
												if (resp.status == 0) {
													voteResult = resp.entity;
													// alert(voteResult.voteTask.title);
													$("#viewResultsVoteTitle")
															.text(
																	voteResult.voteTask.title);
													$("#viewResultsVoteOwner")
															.text(
																	voteResult.voteOwner.name);
													$(
															"#viewResultsVoteDeadLine")
															.text(
																	voteResult.voteTask.deadLine);
													$("#viewResultsVotetDescr")
															.text(
																	voteResult.voteTask.description);
													if (voteResult.voteTask.voteType == 0) {
														$(
																"#viewResultsVotetype")
																.text("分值型");
													} else {
														$(
																"#mviewResultsVotetype")
																.text("选择型");
													}

													// 投票参与人
													var impNames = "";
													if (voteResult.voteImpList == undefined) {
														impNames = "无添加投票参与人";
													} else if (voteResult.voteImpList.length == 1) {
														impNames = voteResult.voteImpList[0].name;

													} else {
														impNames = voteResult.voteImpList[0].name;
														for (var i = 1; i < voteResult.voteImpList.length; i++) {
															impNames = impNames
																	+ "|"
																	+ voteResult.voteImpList[i].name;
														}
													}
													$("#viewResultsImpsSpan")
															.text(impNames);

													// 分阅人
													var readerNames = "";
													if (voteResult.voteReaList == undefined) {
														readerNames = "未添加投票结果查看人";
													} else if (voteResult.voteReaList.length == 1) {
														readerNames = voteResult.voteReaList[0].name;

													} else {
														readerNames = voteResult.voteReaList[0].name;
														for (var i = 1; i < voteResult.voteReaList.length; i++) {
															readerNames = readerNames
																	+ "|"
																	+ voteResult.voteReaList[i].name;
														}
													}
													$("#viewResultsReadersSpan")
															.text(readerNames);

													// 暂未投票人员
													var unImpNames = "";
													if (voteResult.voteNoImpList == null) {
														unImpNames = "全部完成投票";
													} else if (voteResult.voteNoImpList.length == 1) {
														unImpNames = voteResult.voteNoImpList[0].name;
													} else {
														unImpNames = voteResult.voteNoImpList[0].name;
														for (var i = 1; i < voteResult.voteNoImpList.length; i++) {
															unImpNames = unImpNames
																	+ "|"
																	+ voteResult.voteNoImpList[i].name;
														}
													}
													$("#viewResultsUnImpsSpan")
															.text(unImpNames);

													// 添加 查看投票人员投票结果select
													$("#impVoteResultView")
															.append(
																	"<option value=\"defaultSelect\">总体</option>");
													for (var i = 0; i < voteResult.voteImpList.length; i++) {
														$("#impVoteResultView")
																.append(
																		"<option value=\""
																				+ voteResult.voteImpList[i].id
																				+ "\">"
																				+ voteResult.voteImpList[i].name
																				+ "</option>");
													}
													$("#impVoteResultView")
															.val(
																	"defaultSelect");

													// 权限判断，如用户不是任务创建者，不允许看分阅人查看每个人投票结果
													if (voteResult.voteOwner.id != thisUser.id) {
														$("#viewResultsReaders")
																.hide();
														$("#impVoteResultView")
																.hide();
													}
													// 输出统计结果
													// alert(JSON.stringify(voteResult.voteScore));
													showVoteResultsTable(voteResult.voteScore);
													$("#impVoteResultView")
															.change(
																	function() {
																		var tmpId = $(
																				this)
																				.children(
																						'option:selected')
																				.val();
																		if (tmpId == "defaultSelect") {
																			doDisVoteTask(voteResult.voteTask.id);

																		} else {
																			$(
																					"#voteOpResults")
																					.load(
																							"parts/voteManageViewResultsSelect.html",
																							function() {
																								request = new Object();
																								request.operation = "getVoteScoreDetail";
																								request.jsonObject = new Object();
																								request.jsonObject.userId = tmpId;
																								request.jsonObject.voteId = voteResult.voteTask.id;
																								$
																										.post(
																												"Gate",
																												{
																													req : JSON
																															.stringify(request)
																												},
																												function(
																														data,
																														status) {
																													if (status == "success") {
																														var resp = eval("("
																																+ data
																																+ ')');
																														// alert(resp.entity);
																														viewResultsTaskOptionsPer(resp.entity);
																													} else {
																														alert("HTTP请求异常，请重新登陆！");
																														self.location = "login.html";
																													}
																												});

																							});
																		}
																	});
												}
											}
										});
					});
}

// 投票管理内 结果查看页面 的table加载
function showVoteResultsTable(data) {
	var i = 1;
	$('#viewResultsTaskOptions').DataTable({
		"data" : data,
		"columns" : [ {
			"data" : 'voteOptionName',
			"width" : "150px",
			"orderable" : true,
			"render" : function(data, type, row, meta) {
				if (type == "display") {
					return "<td class=\"center\">" + data + "</td>";
				} else {
					return data;
				}
			}
		}, {
			"data" : 'sum',
			"width" : "80px",
			"orderable" : true,
			"render" : function(data, type, row, meta) {
				if (type == "display") {
					return "<td class=\"center\">" + data + "</td>";
				} else {
					return data;
				}
			}
		}, {
			"data" : 'avg',
			"width" : "80px",
			"orderable" : true,
			"render" : function(data, type, row, meta) {
				if (type == "display") {
					return "<td class=\"center\">" + data + "</td>";
				} else {
					return data;
				}
			}
		} ],
		"order" : [ 2, 'desc' ],
		"oLanguage" : {// 语言设置
			"sLengthMenu" : "每页显示 _MENU_ 条记录",
			"sZeroRecords" : "没有检索到数据",
			"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
			"sInfoEmtpy" : "没有数据",
			"sProcessing" : '<i class="fa fa-coffee"></i> 正在加载数据...',
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "<span class=\"fa fa-chevron-left\">",
				"sNext" : "<span class=\"fa fa-chevron-right\">",
				"sLast" : "尾页"
			},
			"sSearch" : "搜索 "
		}
	});
}

// 点击投票页面的取消按钮，重新加载 参与投票 页面
function myVoteCan() {
	$("#page-wrapper").load("parts/voteManageMyVote.html");
}

// 根据userId和voteId查看投票结果，showviewResultsTaskOptions 方法

function viewResultsTaskOptionsPer(data) {
	var i = 1;
	$('#viewResultsTaskOptionsPer')
			.DataTable(
					{
						"data" : data,
						"columns" : [
								{
									"data" : 'score.id',
									"width" : "30px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<tr class=\"odd gradeX\"><td class=\"center\">"
													+ (i++) + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'voteOptionName',
									"width" : "150px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td>";
										} else {
											return data;
										}
									}
								},
								{
									"data" : 'score.score',
									"width" : "80px",
									"orderable" : true,
									"render" : function(data, type, row, meta) {
										if (type == "display") {
											return "<td class=\"center\">"
													+ data + "</td></tr>";
										} else {
											return data;
										}
									}
								} ],
						"order" : [ 0, 'asc' ],
						"oLanguage" : {// 语言设置
							"sLengthMenu" : "每页显示 _MENU_ 条记录",
							"sZeroRecords" : "没有检索到数据",
							"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
							"sInfoEmtpy" : "没有数据",
							"sProcessing" : '<i class="fa fa-coffee"></i> 正在加载数据...',
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "<span class=\"fa fa-chevron-left\">",
								"sNext" : "<span class=\"fa fa-chevron-right\">",
								"sLast" : "尾页"
							},
							"sSearch" : "搜索 "
						}
					});
}

function voteManageViewCan() {
	$("#page-wrapper").load("parts/voteManage.html");
}

// 投票管理首页 右侧添加按钮，与Enter键作用一致。
function voteManageAddNewVoteTask() {
	if ($("#newVoteTaskTitle").val() == "") {
		alert("任务标题不能为空");
		return;
	}
	if ($("#newVoteTaskTitle").val() == lastVoteTaskTitle) {
		warn("请勿重复创建任务！");
		$(this).val("");
		return;
	}
	// alert("qingqiu");
	// newVoteTask.userId = 0;
	newVoteTask.title = $(newVoteTaskTitle).val();
	newVoteTask.deadLine = $("#newVoteTaskDate").val();
	// newVoteTask.deadLine="2017-12-12";
	newVoteTask.voteType = 0;
	newVoteTask.completion = "0/0";
	getJson(createOperation('addVoteTask', newVoteTask), function(data) {
		if (data.status == 0) {
			// getTaskList();
			addNewVoteTaskNode(correctTaskItem(data.entity), $(
					"#voteTaskListTable").DataTable());
			lastVoteTaskTitle = data.entity.voteTask.title;
			$("#newVoteTaskTitle").val("");
			// alert("添加一个新任务");
		} else
			warn(data.message);
	}, function(status, err) {
		warn("REQ STAT=" + status + "\nERR:" + err);
	});

}